// Kony


#include "UI/Widget/DraggingUserWidget.h"
#include "UI/Widget/BaseUserWidget.h"
#include "Components/CanvasPanelSlot.h"
#include "Blueprint/WidgetLayoutLibrary.h"
#include "Components/Overlay.h"
#include "Components/PanelWidget.h"

void UDraggingUserWidget::NativeConstruct()
{
	Super::NativeConstruct();
	if (!ensure(DraggingCanvas && OverlayRoot)) return;
	OverlayRoot->SetRenderTransformPivot(FVector2D(0.5f, 0.5f));
}

FReply UDraggingUserWidget::NativeOnMouseWheel(const FGeometry& InGeometry, const FPointerEvent& InMouseEvent)
{
	float ScrollDelta = InMouseEvent.GetWheelDelta();
	CurrentZoom = FMath::Clamp(CurrentZoom + ScrollDelta * 0.1f, 0.5f, 3.0f);
	
	// 直接对自身进行缩放
	if (OverlayRoot)
	{
		OverlayRoot->SetRenderScale(FVector2D(CurrentZoom, CurrentZoom));
	}
	else
	{
		SetRenderScale(FVector2D(CurrentZoom, CurrentZoom));
	}
	return FReply::Handled();
}

FReply UDraggingUserWidget::NativeOnMouseMove(const FGeometry& InGeometry, const FPointerEvent& InMouseEvent)
{
	// 如果正在拖拽，完全参考MapWidget的实现方式
	if (bIsDragging)
	{
		if (bDragging)
		{
			FVector2D CurrentScreenPos = InMouseEvent.GetScreenSpacePosition();

			// 把屏幕 delta 转换为地图父级坐标空间 delta
			FVector2D LocalDelta = InGeometry.AbsoluteToLocal(CurrentScreenPos) - InGeometry.AbsoluteToLocal(LastMouseScreenPos);

			// 更新位置 - 优先使用DraggingOverlayRoot，否则使用自身
			if (OverlayRoot)
			{
				FVector2D CurrentTranslation = OverlayRoot->GetRenderTransform().Translation;
				OverlayRoot->SetRenderTranslation(CurrentTranslation + LocalDelta);
			}
			else
			{
				FVector2D CurrentTranslation = GetRenderTransform().Translation;
				SetRenderTranslation(CurrentTranslation + LocalDelta);
			}

			LastMouseScreenPos = CurrentScreenPos;

			return FReply::Handled();
		}
	}
	return FReply::Unhandled();
}

FReply UDraggingUserWidget::NativeOnMouseButtonDown(const FGeometry& InGeometry, const FPointerEvent& InMouseEvent)
{
	if (InMouseEvent.GetEffectingButton() == EKeys::LeftMouseButton)
	{
		bDragging = true;
		LastMouseScreenPos = InMouseEvent.GetScreenSpacePosition();
		return FReply::Handled();
	}
	return FReply::Unhandled();
}

FReply UDraggingUserWidget::NativeOnMouseButtonUp(const FGeometry& InGeometry, const FPointerEvent& InMouseEvent)
{
	if (InMouseEvent.GetEffectingButton() == EKeys::LeftMouseButton)
	{
		bDragging = false;
		return FReply::Handled();
	}
	return FReply::Unhandled();
}
